package com.example.mynewsapp.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.example.mynewsapp.R
import com.example.mynewsapp.fragment.*
import com.example.mynewsapp.fragment.Fragment.db
import com.example.mynewsapp.fragment.news_history_favor.FragmentFavoriteNews
import com.example.mynewsapp.fragment.news_history_favor.FragmentHistoryNews
import com.example.mynewsapp.util.DatabaseHelper
import com.ismaeldivita.chipnavigation.ChipNavigationBar
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    var item = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //依靠DatabaseHelper的构造函数创建数据库
        val dbHelper = DatabaseHelper(this, "news_db", null, 1)
        db = dbHelper.writableDatabase

        // 刚开始进入时
        bottomNavigation.setItemSelected(R.id.menuHeadline, true)
        // 打开热点新闻页面
        setupFragment(FragmentNews())

        // 点击按钮打开不同的页面
        bottomNavigation.setOnItemSelectedListener(object : ChipNavigationBar.OnItemSelectedListener {
            override fun onItemSelected(id: Int) {
                when (id) {
                    R.id.menuHeadline -> setupFragment(FragmentNews())
                    R.id.menuHistory -> setupFragment(FragmentHistory())
                    R.id.menuVideo -> setupFragment(FragmentVideo())
                    R.id.menuFavorite -> setupFragment(FragmentFavorite())
//                    R.id.menuWeather -> setupFragment(WeatherActivity())
                    R.id.menuSearch -> setupFragment(FragmentSearch())
                }
            }
        })
    }

    private fun setupFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.fragmentLayout, fragment)
        transaction.commitAllowingStateLoss()
    }


}

